package com.zjfgz.lib_kt_com.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import com.xiasuhuei321.loadingdialog.view.LoadingDialog
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import java.net.SocketTimeoutException
import kotlin.coroutines.CoroutineContext

abstract class BaseFragment : Fragment() , CoroutineScope {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(getLayout(), container, false)
    }

    lateinit var ld : LoadingDialog

    private val job by lazy { SupervisorJob() }

    val messageLiveData by lazy { MutableLiveData<String>() }

    val loadingLiveData by lazy { MutableLiveData<Boolean>() }

    val handler = CoroutineExceptionHandler { _, throwable ->
        when (throwable) {
            is SocketTimeoutException -> onJobError("网络超时")
            else -> onJobError(throwable.message.toString())
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initSubScribe()
        initView()
        ld = LoadingDialog(activity)
        ld.setLoadingText("加载中")
            .setSuccessText("加载成功")
            .setFailedText("加载失败")
            .setInterceptBack(false)
    }

    open fun onJobError(msg: String) {
        messageLiveData.postValue(msg)
        loadingLiveData.postValue(false)
    }

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.IO + job + handler

    abstract fun getLayout():Int
    abstract fun initView()
    abstract fun initSubScribe()
}